package com.maomao.SMSUtil;

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author admin
 * @date 2018/4/4
 */
public class EncodedUtil {
    public static void main(String[] args) {
        System.out.println(getMD5Str("hzjbyzm1015"));
        System.out.println(base64Encode("您的验证码：123456"));
        System.out.println(getRandom());
    }

    /**
     * MD5加密
     * @param str
     * @return
     */
    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException var5) {
            System.exit(-1);
        } catch (UnsupportedEncodingException var6) {
            var6.printStackTrace();
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();

        for(int i = 0; i < byteArray.length; ++i) {
            if(Integer.toHexString(255 & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(255 & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(255 & byteArray[i]));
            }
        }

        return md5StrBuff.toString();
    }

    /**
     * base64编码
     * @param pBytes
     * @return
     */
    public static String base64Encode(byte[] pBytes) {
        BASE64Encoder base64 = new BASE64Encoder();
        return base64.encode(pBytes);
    }

    /**
     * base64编码
     * @param str
     * @return
     */
    public static String base64Encode(String str) {
        try {
            return base64Encode(str.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getRandom() {
        return (int)((Math.random()*9+1)*100000);
    }
}
